<template>
  <div>
    <InsertTagDialog ref="insertTagDialog" @saveTag="saveTag"/>
    <TransferTagDialog ref="transferTagDialog"
                       :selectedTopTag="selectedTopTag"
                       :selectedSubTag="selectedSubTag"
                       @transfer="selectSubTagTree"/>

    <TransferKnowledgeDialog ref="transferKnowledgeDialog"
                             :subTagTree="subTagTree"
                             :selectedSubTag="selectedSubTag"/>
    <el-container>
      <el-aside width="300px">
        <el-header height="40px">
          <el-button icon="el-icon-plus" style="width: 100%; " @click="insertTopTag">新建一级分类</el-button>
        </el-header>
        <el-main style="padding-top: 5px; ">
          <el-table highlight-current-row ref='topTagTable' :data="topTagList" :height="tableHeight"
                    @current-change="handleTopTagChange">
            <el-table-column prop="name"
                             label="分类标签列表">
              <template slot-scope="scope">
                <div @mouseenter="handleMouseOver(scope.row)" @mouseleave="handleMouseOut(scope.row)">
                  <span>{{ scope.row.name }}</span>
                  <el-button v-if="scope.row.showButton && !isShow" class="inline reorder-button" icon="el-icon-edit"
                             title="修改"
                             @click.stop="editTag(scope.row)"></el-button>
                  <el-button v-if="scope.row.showButton && !isShow" class="inline reorder-button" icon="el-icon-delete"
                             plain title="删除"
                             type="danger" @click.stop="deleteTopTag(scope.row)"></el-button>
                  <el-button v-if="scope.row.showButton && !isShow && scope.$index !== 0" class="inline reorder-button" icon="el-icon-top"
                             title="上移"
                             @click.stop="topTagMoveUp(scope.row)"></el-button>
                  <el-button v-if="scope.row.showButton && !isShow && scope.$index !== topTagList.length -1" class="inline reorder-button" icon="el-icon-bottom"
                             title="下移"
                             @click.stop="topTagMoveDown(scope.row)"></el-button>
                  <el-button v-if="scope.row.showButton && !isShow" class="inline reorder-button"
                             icon="el-icon-download"
                             title="下载" @click.stop="downloadTagTree(scope.row)"></el-button>
                  <el-button v-if="scope.row.showButton && !isShow" class="inline reorder-button" icon="el-icon-refresh"
                             title="推送"
                             @click.stop="syncTopTag(scope.row)"></el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-aside>
      <el-main style="padding-left: 10px; ">
        <el-row height="40px">
          <el-col :span="4">
            <el-button type="primary" icon="el-icon-plus" @click="insertSubTag(selectedTopTag)">新建二级分类</el-button>
          </el-col>
          <el-col :span='4'>
            <el-button icon="el-icon-download" @click="downloadImportTagTemplate">下载导入模板</el-button>
          </el-col>
          <el-col :span="10" :offset="6">
            <el-input placeholder="请输入名称或编码" v-model="searchInput" @keyup.enter.native="searchConfirm">
              <el-button slot="append" icon="el-icon-search" @click="searchConfirm"></el-button>
            </el-input>
          </el-col>
        </el-row>
        <el-row style="padding-top: 5px; ">

          <u-table :data="subTagTree"
                   ref='subTagTable'
                   :border="false"
                   :data-changes-scroll-top="false"
                   :height="tableHeight"
                   :row-class-name="getRowClassName"
                   :treeConfig="{
                     children: 'children',
                     iconClose: 'el-icon-arrow-right',
                     iconOpen: 'el-icon-arrow-down',
                     expandAll: false,
                     expandRowKeys: expandRowKeyArray}"
                   beautify-table highlight-current-row row-id="id"
                   row-key="id"
                   use-virtual
                   @toggle-tree-expand="toggleTreeExpand"
                   @current-change="handleSubTagChange">
            <u-table-column prop="name"
                            :tree-node="true"
                            label="分类名称" show-overflow-tooltip>
            </u-table-column>
            <u-table-column prop="tagCode"
                            label="分类编码" width="200" show-overflow-tooltip>
            </u-table-column>
            <u-table-column prop="index"
                            label="排序" width="50">
              <template slot-scope="scope">
                <span>{{ scope.row.index + 1 }}</span>
              </template>
            </u-table-column>
            <u-table-column label="操作" width="350">
              <template slot-scope="scope">
                <el-upload v-show="scope.row.selfDefinedFlag" style="display: inline-block"
                           :action="'/pmph/action/tag/uploadAndInsertTagFile?supTagId=' + scope.row.id"
                           accept=".xlsx" :show-file-list="false"
                           :on-success="uploadAndInsertTagFileSuccess">
                  <span><el-link @click.prevent="">上传</el-link></span>
                </el-upload>
                <span><el-link v-if="!isShow" @click.prevent="insertSubTag(scope.row)">新增</el-link></span>
                <span><el-link v-if="!isShow" @click.prevent="editTag(scope.row)">编辑</el-link></span>
                <span><el-link v-if="!isShow" type="danger" @click.prevent="deleteSubTag(scope.row)">删除</el-link></span>
                <span><el-link v-if="!isShow" @click.prevent="transferTag(scope.row)">转移标签</el-link></span>
                <span><el-link v-if="!isShow" @click.prevent="transferKnowledge(scope.row)">转移知识</el-link></span>
                <span><el-link v-if="!isShow" :disabled="scope.row.index === 0"
                               @click.prevent="subTagMoveUp(scope.row)">上移</el-link></span>
                <span><el-link v-if="!isShow" :disabled="setDownDisabled(scope.row)"
                               @click.prevent="subTagMoveDown(scope.row)">下移</el-link></span>
              </template>
            </u-table-column>
          </u-table>
        </el-row>
      </el-main>
    </el-container>
  </div>
</template>
<script>
import InsertTagDialog from "./InsertTagDialog";
import TransferTagDialog from "./TransferTagDialog";
import TransferKnowledgeDialog from "./TransferKnowledgeDialog";

export default {
  name: "TagIndex",
  components: {InsertTagDialog, TransferTagDialog, TransferKnowledgeDialog},
  data() {
    return {
      topTagList: [],
      subTagList: [],
      subTagMap: [],
      subTagTree: [],
      tableHeight: 0,
      selectedTopTag: {},
      selectedSubTag: {},
      rowClassNameList: ['secondLevelRowClass', 'thirdLevelRowClass', 'fourthLevelRowClass', 'fifthLevelRowClass'],
      searchInput: '',
      expandRowKeyArray: [],
      isShow: false
    }
  },
  methods: {
    toggleTreeExpand() {
      this.expandRowKeyArray = this.$refs.subTagTable.getTreeExpandRecords().map(item => item.id)
    },
    downloadImportTagTemplate() {
      window.location.href = '/pmph/action/tag/downloadImportTagTemplate'
    },
    syncTopTag(row) {
      this.axios.get('/pmph/action/tag/syncTopTag', {
        params: {
          topTagId: row.id
        }
      }).then(() => {
      })
    },
    transferTag(row) {
      this.selectedSubTag = row
      this.$refs.transferTagDialog.visible = true
    },
    transferKnowledge(row) {
      this.selectedSubTag = row
      this.$refs.transferKnowledgeDialog.visible = true
    },
    downloadTagTree(row) {
      window.location.href = '/pmph/action/tag/downloadTagTree?tagId=' + row.id
    },
    uploadAndInsertTagFileSuccess(respose, file) {
      if (respose.code === 1) {
        this.selectSubTagTree()
      } else {
        this.$message.error(respose.msg)
      }
    },
    topTagMoveUp(row) {
      let index = this.topTagList.findIndex(item => item === row)
      let preRow = this.topTagList[index - 1]
      this.topTagList.splice(index - 1, 1, row)
      this.topTagList.splice(index, 1, preRow)
      row.index = index - 1
      preRow.index = index

      this.axios.post('/pmph/action/tag/topTagMoveUp',
        UTIL.parse2FormData({
          tag: row,
          preTag: preRow}))
    },
    topTagMoveDown(row) {
      let index = this.topTagList.findIndex(item => item === row)
      let nextRow = this.topTagList[index + 1]
      this.topTagMoveUp(nextRow)
    },
    subTagMoveUp(row) {
      let preRow = this.subTagMap[row.parentId].children[row.index - 1]
      let param = new URLSearchParams()
      param.append("tag", JSON.stringify(row))
      param.append("preTag", JSON.stringify(preRow))
      this.axios.post('/pmph/action/tag/subTagMoveUp', param).then(() => {
        this.selectSubTagTree()
      })
    },
    subTagMoveDown(row) {
      // 相当于对下一行进行上移操作;
      let nextRow = this.subTagMap[row.parentId].children[row.index + 1]
      this.subTagMoveUp(nextRow)
    },
    handleMouseOver(row) {
      this.$set(row, 'showButton', true)
    },
    handleMouseOut(row) {
      this.$set(row, 'showButton', false)
    },
    insertTopTag() {
      this.$refs.insertTagDialog.type = 'insert'
      this.$refs.insertTagDialog.visible = true
      this.$refs.insertTagDialog.tag.index = this.topTagList.length
      this.$refs.insertTagDialog.tag.level = 1
      this.$refs.insertTagDialog.tag.rootId = this.$refs.insertTagDialog.tag.id
      this.$refs.insertTagDialog.siblingTagList = this.topTagList
    },
    editTag(row) {
      this.$refs.insertTagDialog.type = 'update'
      this.$refs.insertTagDialog.visible = true
      this.$refs.insertTagDialog.tag.id = row.id
      this.$refs.insertTagDialog.tag.index = row.index
      this.$refs.insertTagDialog.tag.level = row.level
      this.$refs.insertTagDialog.tag.name = row.name
      this.$refs.insertTagDialog.tag.parentId = row.parentId
      this.$refs.insertTagDialog.tag.rootId = row.rootId
      this.$refs.insertTagDialog.tag.tagCode = row.tagCode
      this.$refs.insertTagDialog.tag.selfDefinedFlag = row.selfDefinedFlag
      if (row.level === 1) {
        this.$refs.insertTagDialog.siblingTagList = this.topTagList
      } else {
        this.$refs.insertTagDialog.siblingTagList = this.subTagMap[row.parentId].children
      }
    },
    deleteTopTag(row) {
      this.$confirm('确认删除分类标签及子标签?', '确认', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let param = new URLSearchParams()
        param.append("tag", JSON.stringify(row))
        this.axios.post('/pmph/action/tag/deleteTopTag', param).then(() => {
          this.selectTopTagList()
        })
      })
    },
    deleteSubTag(row) {
      this.$confirm('确认删除分类标签及子标签?', '确认', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let param = new URLSearchParams()
        param.append("tag", JSON.stringify(row))
        this.axios.post('/pmph/action/tag/deleteSubTag', param).then(() => {
          this.selectSubTagTree()
        })
      })
    },
    insertSubTag(row) {
      if (!row.children) {
        row.children = []
      }
      this.$refs.insertTagDialog.type = 'insert'
      this.$refs.insertTagDialog.visible = true
      this.$refs.insertTagDialog.tag.index = row.children.length
      this.$refs.insertTagDialog.tag.level = row.level + 1
      this.$refs.insertTagDialog.tag.selfDefinedFlag = this.selectedTopTag.selfDefinedFlag
      if (this.selectedTopTag.selfDefinedFlag) {
        this.$refs.insertTagDialog.tag.tagCode = row.tagCode + '.' + ('00' + (row.children.length + 1)).substr(-3)
      }
      this.$refs.insertTagDialog.tag.parentId = row.id
      this.$refs.insertTagDialog.tag.parentName = row.name
      this.$refs.insertTagDialog.tag.rootId = this.selectedTopTag.id
      this.$refs.insertTagDialog.siblingTagList = row.children
    },
    saveTag(tag) {
      // 重新加载页面;
      if (tag.level === 1) {
        this.selectTopTagList()
      } else {
        this.selectSubTagTree()
      }
    },
    handleTopTagChange(row) {
      this.selectedTopTag = row
    },
    handleSubTagChange(row) {
      this.selectedSubTag = row
    },
    getRowClassName(scope) {
      if (scope.row.filtered) {
        return 'filteredRow'
      }
      return this.rowClassNameList[scope.row.level - 2]
    },
    setDownDisabled(row) {
      if (row.level === 2) {
        return row.index === this.subTagTree.length - 1
      }
      return row.index === this.subTagMap[row.parentId].children.length - 1
    },
    sleep(d) {
      for (var t = Date.now(); Date.now() - t <= d;) ;
    },
    searchConfirm() {
      if (this.searchInput) {
        // 先重置选中行, 再重新渲染页面, 再递归展开;
        for (let item of this.subTagList) {
          this.$set(item, 'filtered', false)
          if (item.name.includes(this.searchInput) || item.tagCode.includes(this.searchInput)) {
            this.$set(item, 'filtered', true)
          }
        }
        this.$refs.subTagTable.reloadData(this.subTagTree)
        for (let item of this.subTagList) {
          if (item.name.includes(this.searchInput) || item.tagCode.includes(this.searchInput)) {
            this.recursiveExpandRow(item)
          }
        }
        // 表格展开状态有变化, 手工绑定已展开节点;
        this.expandRowKeyArray = this.$refs.subTagTable.getTreeExpandRecords().map(item => item.id)
      }
    },
    recursiveExpandRow(item) {
      // 递归展开父节点, 父节点可能还未渲染, 所以需要从二级节点向下展开;
      let supNodeArray = []
      while (item.level > 1) {
        item = this.subTagMap[item.parentId]
        supNodeArray.unshift(item)
      }
      for (let supNode of supNodeArray) {
        this.$refs.subTagTable.setTreeExpansion(supNode, true)
      }
    },
    selectTopTagList() {
      this.axios.get('/pmph/action/tag/selectTopTagList').then((response) => {
        this.topTagList = response.data;
        this.$refs.topTagTable.setCurrentRow(this.topTagList[0])
      })
    },
    selectSubTagTree() {
      this.axios.get('/pmph/action/tag/selectSubTagListByTopTagId', {
        params: {
          topTagId: this.selectedTopTag.id
        }
      }).then((response) => {
        this.subTagList = response.data
        this.subTagTree = []
        this.subTagMap = {}
        this.selectedTopTag.children = this.subTagTree
        this.subTagMap[this.selectedTopTag.id] = this.selectedTopTag
        for (let item of response.data) {
          this.$set(item, 'filtered', false)
          if (this.searchInput &&
            (item.name.includes(this.searchInput) || item.tagCode.includes(this.searchInput))) {
            this.$set(item, 'filtered', true)
          }
          this.subTagMap[item.id] = item
          if (item.level === 2) {
            this.subTagTree.push(item)
          } else {
            let parentTag = this.subTagMap[item.parentId]
            if (!parentTag.children) {
              parentTag.children = []
            }
            this.subTagMap[item.parentId].children.push(item)
          }
        }
        this.$refs.subTagTable.reloadData(this.subTagTree)
      })
    }
  },
  watch: {
    selectedTopTag() {
      this.expandRowKeyArray = []
      this.selectSubTagTree()
    }
  },
  created() {
    this.tableHeight = CONST.WORKSPACE_HEIGHT - 55
    this.selectTopTagList()
    if (this.$store.state.user.userName === 'admin') {
      return
    }
    //角色Id等于管理员角色
    for (let i = 0; i < this.$store.state.user.roleIds.length; i++) {
      if (this.$store.state.user.roleIds[i] === '1455781731549327361') {
        return;
      }
    }
    UTIL.findTreeNode(this.$store.state.menuList, item => {
      if (item.id === this.$store.state.activeId) {
        if (item.detailButton && item.editButton) {
          this.isShow = false
        } else {
          if (item.detailButton) {
            this.isShow = true
          } else {
            this.isShow = false
          }
        }

      }
    })
  }
}
</script>
<style scoped>

.inline {
  display: inline-block;
}

.reorder-button {
  width: 20px;
  height: 20px;
  border-radius: 10px;
  padding: 0;
  margin: 0;
}

.el-header {
  padding: 0px;
}

.el-aside {
  padding: 0px;
}

.el-main {
  padding: 0px;
}

/deep/ .filteredRow {
  background-color: lightgreen !important;
}

/deep/ .el-table__expand-icon {
  margin-right: 0px !important;
}

/deep/ .secondLevelRowClass {
  background-color: #fff !important;
}

/deep/ .thirdLevelRowClass {
  background-color: #e6f7ff !important;
}

/deep/ .fourthLevelRowClass {
  background-color: #bae7ff !important;
}

/deep/ .fifthLevelRowClass {
  background-color: #69c0ff !important;
}

/deep/ .sixthLevelRowClass {
  background-color: #eaf8f6 !important;
}

/deep/ ::-webkit-scrollbar {
  width: 5px;
  height: 5px;
  background-color: #F5F5F5;
}

/deep/ ::-webkit-scrollbar-thumb {
  border-radius: 5px;
  -webkit-box-shadow: inset 0 0 2px rgba(0, 0, 0, .3);
  background-color: #B3C0D1;
}

/deep/ .el-table__body {
  margin: 0px !important;
  width: 100% !important;
}

</style>
